package com.cc.spring.interceptors;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.InvalidClaimException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.cc.spring.utils.HdfsUtil;
import com.cc.spring.utils.JWTUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// 自定义拦截器
@Component
public class JwtInterceptor implements HandlerInterceptor {
    private static final Logger LOG = LoggerFactory.getLogger(HdfsUtil.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // OPTIONS请求不做校验,
        // 前后端分离的架构, 前端会发一个OPTIONS请求先做预检, 对预检请求不做校验
        if("OPTIONS".equals(request.getMethod().toUpperCase())){
            return true;
        }
        String token = request.getHeader("token");
//        请求完成时间
        long startTime = System.currentTimeMillis();
        request.setAttribute("requestStartTime",startTime);
        if( token == null || token.equals("")){
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            LOG.info("token为空");
            return false;
        }
        try {
            JWTUtil.verifyToken(token);
//            表示检验通过
            return true;
//            出现了异常表示检验失败
        }catch (SignatureVerificationException e) {
            e.printStackTrace();
            LOG.info("签名不一致");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
        }catch (TokenExpiredException e) {
            e.printStackTrace();
            LOG.info("令牌过期异常");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
        }catch (AlgorithmMismatchException e) {
            e.printStackTrace();
            LOG.info("算法不匹配");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
        }catch (InvalidClaimException e) {
            e.printStackTrace();
            LOG.info("失效的claim异常");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
        }catch (Exception e) {
            e.printStackTrace();
            LOG.info("系统异常");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
        }

        return false;
    }

//    完成请求后所执行的方法
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        long requestStartTime = (long) request.getAttribute("requestStartTime");
//        LOG.info("----------LoginInterceptor 结束 耗时:{}ms------------",System.currentTimeMillis() - requestStartTime);
    }
}
